package kr.hkit.androidcomplete03.DomParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.DomParser.common.DaeGuWeatherItem;
import kr.hkit.androidcomplete03.DomParser.common.DaeguItem;
import kr.hkit.androidcomplete03.DomParser.common.MyAdapterList;
import kr.hkit.androidcomplete03.DomParser.common.MyWeatherAdapter;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class KMAPullParse extends Activity {
	final static String TAG = "DEBUG Weather PULLPARSER";
	ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weatherparser);
		list = (ListView) findViewById(R.id.weatherlistview);
		new ParsingXml().execute("http://www.kma.go.kr/XML/weather/sfc_web_map.xml");
		Log.d(TAG, "HEY! - onCreate()");
	}

	private class ParsingXml extends
			AsyncTask<String, Void, ArrayList<DaeGuWeatherItem>> {
		ProgressDialog progressDlg;

		@Override
		protected void onPreExecute() {
			Log.d(TAG, "HEY! - onPreExecute()");
			progressDlg = ProgressDialog.show(KMAPullParse.this, "Wait",
					"날씨정보 불러오는중 ...");
		}

		protected ArrayList<DaeGuWeatherItem> doInBackground(String... params) {
			Log.d(TAG, "HEY! - doInBackground()");
			StringBuffer sb = new StringBuffer();
			BufferedReader br = null;
			HttpURLConnection con = null;
			String line = null;
			try {
				URL url = new URL(params[0].toString());
				con = (HttpURLConnection) url.openConnection();
				if (con != null) {
					con.setConnectTimeout(10000);
					con.setUseCaches(false);
					if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
						br = new BufferedReader(new InputStreamReader(
								con.getInputStream(), "UTF-8"));
					}
				}
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
					con.disconnect();
				} catch (Exception e) {
				}
			}

			return parsingXml(sb.toString());
		}

		@Override
		protected void onPostExecute(ArrayList<DaeGuWeatherItem> result) {
			Log.d(TAG, "HEY! - onPostExecute()");
			progressDlg.dismiss();

			MyWeatherAdapter adapter = new MyWeatherAdapter(KMAPullParse.this, result);
			// MyAdapterList adapter = new MyAdapterList(DGDomParse.this,
			// R.layout.datarow, result);

			list.setAdapter(adapter);
		}
	}

	private ArrayList<DaeGuWeatherItem> parsingXml(String xml) {
		ArrayList<DaeGuWeatherItem> arList = new ArrayList<DaeGuWeatherItem>();
		DaeGuWeatherItem item = null;
		boolean initItem = false;

		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();

			parser.setInput(new StringReader(xml));
			
			int eventType = parser.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					Log.d(TAG, "START_DOCUMENT");
					
					break;

				case XmlPullParser.START_TAG:
					Log.d(TAG, "START_TAG");
					if (parser.getName().equalsIgnoreCase("local")) {
						initItem = true;
						item = new DaeGuWeatherItem();
							
					}
				
					for (int i = 0; i < parser.getAttributeCount(); i++) {
						if (parser.getAttributeName(i).equalsIgnoreCase("icon")) {
							item.setIcon(parser.getAttributeValue(i));
						} else if (parser.getAttributeName(i).equalsIgnoreCase("desc")) {
							item.setDesc(parser.getAttributeValue(i));
						} else if (parser.getAttributeName(i).equalsIgnoreCase("ta")) {
							item.setTemp(parser.getAttributeValue(i));
						}
					}
					
					break;

				case XmlPullParser.TEXT:
					Log.d(TAG, "TEXT");
					if (initItem) {
						item.setItemName(parser.getText());
						initItem = false;
					}
					break;

				case XmlPullParser.END_TAG:
					if (parser.getName().equals("local")) {
						arList.add(item);
					}
					Log.d(TAG, "END_TAG");
					break;

				case XmlPullParser.END_DOCUMENT:
					Log.d(TAG, "END_DOCUMENT");
					break;

				}

				eventType = parser.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return arList;
	}
}
